package com.itheima.train.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.train.common.anno.Log;
import com.itheima.train.common.core.JsonResult;
import com.itheima.train.common.exception.GroupBizException;
import com.itheima.train.common.util.CloneDirection;
import com.itheima.train.common.util.ObjectUtils;
import com.itheima.train.domain.CZYGroupDTO;
import com.itheima.train.domain.CZYGroupQuery;
import com.itheima.train.domain.CZYGroupVO;
import com.itheima.train.service.CZYGroupService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/group")
public class CZYGroupController {

	private static final Logger logger = LoggerFactory.getLogger(CZYGroupController.class);

	@Autowired
	private CZYGroupService groupService;

	/**
	 * 查询该管理员创建的组
	 * @param adminId 组查新条件
	 * @return 组信息
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/list/{adminId}")
	@Log("查询该管理员创建的组")
	public JsonResult<List<CZYGroupVO>> listGroup(@PathVariable("adminId") Long adminId) {
		try {
			List<CZYGroupDTO> groups = groupService.findGroupListByAdminId(adminId);
			List<CZYGroupVO> resultGroups = ObjectUtils.convertList(groups,
					CZYGroupVO.class, CloneDirection.OPPOSITE);
			return JsonResult.buildSuccess(resultGroups);
		} catch (GroupBizException e) {
			logger.error("biz error", e);
			return JsonResult.buildError(e.getErrorCode(), e.getErrorMsg());
		}catch (Exception e){
			logger.error("error", e);
			return JsonResult.buildError(e.getMessage());
		}
	}


	/**
	 * 分页查询，此接口只做示例
	 * @param
	 * @return 组信息
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/page")
	public JsonResult<PageInfo<CZYGroupDTO>> listGroup(@RequestBody CZYGroupQuery query) {
		try {
			PageInfo<CZYGroupDTO> groups = groupService.findGroupListPage(query);
			return JsonResult.buildSuccess(groups);
		} catch (GroupBizException e) {
			logger.error("biz error", e);
			return JsonResult.buildError(e.getErrorCode(), e.getErrorMsg());
		}catch (Exception e){
			logger.error("error", e);
			return JsonResult.buildError(e.getMessage());
		}
	}

}
